package com.example.juccode.sync;

/**
 * author: 刘中魁
 */
public class SaleTicket {
    //创建多个线程 调用资源类的操作方法
    public static void main(String[] args) {
        //创建 ticket对象
        Ticket ticket = new Ticket();
        int num = 40;
        //创建三个线程
        // 1
        new Thread(() -> {
            for (int i = 0; i < num; i++) {
                ticket.sale();
            }

        },"AA").start();
        // 2
        new Thread(() -> {
            for (int i = 0; i < num; i++ ){
                ticket.sale();
            }
        },"BB").start();
        // 3
        new Thread(() -> {
            for (int i = 0; i < num; i++){
                ticket.sale();
            }
        },"CC").start();


    }
}

class Ticket {
    // 票数
    private int number = 30;
    //操作方法 卖票
    public synchronized void sale() {
        //判断是否有票
        if (number > 0) {
            number--;
            System.out.println(Thread.currentThread().getName()
                    + "卖出了1张票，剩余" + number + "票");
        }
    }
}
